package org.example.线程;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程交替打印ABC，各个打印50个
 */
public class 线程交替打印 {

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    private static Condition condition3 = lock.newCondition();

    private static volatile int count = 1;
    private final static int MAX_COUNT = 150;

    private static int currPrint = 0;
    private final static int PRINT_SIZE = 3;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint != 0) {
                        condition1.await();
                    }
                    if (count > MAX_COUNT) {
                        break; // 检查是否超过最大打印次数
                    }
                    System.out.println(count + " : A");
                    count++;
                    currPrint++;
                    condition2.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }, "1");
        Thread t2 = new Thread(() -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint != 1) {
                        condition2.await();
                    }
                    if (count > MAX_COUNT) {
                        break; // 检查是否超过最大打印次数
                    }
                    System.out.println(count + " : B");
                    count++;
                    currPrint++;
                    condition3.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }, "2");
        Thread t3 = new Thread(() -> {
            while (count <= MAX_COUNT) {
                lock.lock();
                try {
                    while (currPrint != 2) {
                        condition3.await();
                    }
                    if (count > MAX_COUNT) {
                        break; // 检查是否超过最大打印次数
                    }
                    System.out.println(count + " : C");
                    count++;
                    currPrint++;
                    currPrint %= PRINT_SIZE;
                    condition1.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }, "3");
        t1.start();
        t2.start();
        t3.start();
    }

}